<template>
  <div>
    <el-tag
      v-for="tag in tags"
      :key="tag"
      :type="current_args.type"
      :color="current_args.color"
      :effect="current_args.effect"
      :[closable]="true"
      :[hit]="true"
      size="medium"
      :disable-transitions="false"
      @close="handleClose(tag)"
    >
      {{ tag }}
    </el-tag>
    <el-input
      v-if="inputVisible"
      ref="saveTagInput"
      v-model="inputValue"
      class="input-new-tag"
      size="medium"
      @keyup.enter.native="handleInputConfirm"
      @blur="handleInputConfirm"
    />
    <el-button v-else class="button-new-tag" size="medium" @click="showInput">+ 添加</el-button>
  </div>
</template>

<script>
export default {
  props: {
    value: {
      type: String,
      default: ''
    },
    args: {
      type: Object,
      required: true,
      default: _ => {
        return {};
      }
    }
  },
  data() {
    return {
      current_field: this.$util.isArray(this.value) ? this.value : [],
      current_args: this.args,
      inputVisible: false,
      inputValue: ''
    };
  },
  computed: {
    tags() {
      return this.$util.isArray(this.current_field) ? this.current_field : [];
    },
    closable() {
      return this.current_args.closable == 1 ? 'closable' : null;
    },
    hit() {
      return this.current_args.hit == 1 ? 'hit' : null;
    }
  },
  watch: {
    current_field(value) {
      this.$emit('update:value', value);
    },
    value: {
      handler(now, old) {
        this.current_field = now;
      }
    }
  },
  methods: {
    handleClose(tag) {
      this.current_field.splice(this.current_field.indexOf(tag), 1);
    },
    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    handleInputConfirm() {
      const inputValue = this.inputValue;
      if (inputValue) {
        this.current_field.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = '';
    }
  }
};
</script>

<style>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
